package com.example.config;

import com.example.domain.Order;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 *@description: 自定义 redis 持久化
 */
//@Component
public class RedisStateMachinePersist<S, E> implements StateMachinePersist<S, E, Order> {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public RedisStateMachinePersist(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void write(StateMachineContext<S, E> stateMachineContext, Order order) throws Exception {
        // 构建要保存的状态数据

        // 序列化为 JSON 并保存到 Redis
        String json = objectMapper.writeValueAsString(order);
        redisTemplate.opsForValue().set(order.getId()+"", json);
    }



    @Override
    @SuppressWarnings("unchecked")
    public StateMachineContext<S, E> read(Order order) throws Exception {
        // 从 Redis 获取 JSON
        String json = (String) redisTemplate.opsForValue().get(order.getId());
        if (json == null) {
            return null;
        }

        // 解析状态数据
        Order stateData = objectMapper.convertValue(json, Order.class);
        // todo 实际使用时需返回恢复的状态机
        return new DefaultStateMachineContext(stateData.getStatus(), null, null, null);
    }



}
